package be.nvlooy.moviereminder.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("assembler")
public class Assembler {

	@Transactional(readOnly = true)
	User buildUserFromUserEntity(be.nvlooy.moviereminder.entities.User user) {

		String username = user.getUsername();
		String password = user.getPassword();
		boolean enabled = user.isActive();
		boolean isAdmin = user.isAdmin();
		boolean accountNonExpired = user.isActive();
		boolean credentialsNonExpired = user.isActive();
		boolean accountNonLocked = user.isActive();

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

		authorities.add(new GrantedAuthorityImpl("ROLE_USER"));

		if (isAdmin)
			authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

		User springUser = new User(username, password, enabled,
				accountNonExpired, credentialsNonExpired, accountNonLocked,
				authorities);

		return springUser;
	}
}
